#!/bin/sh


a=$1
b=$2

echo 打包 $a  openresty server

luajit=/usr/local/openresty/luajit/bin/luajit
if [ ! -d /usr/local/openresty/luajit/ ]; then
    #statements
    # echo "not exist"
    luajit=/usr/local/opt/openresty/luajit/bin/luajit
fi

function compile() {
    for file in $1
    do
        echo $file
        filepath=`dirname $file`
        subpath=${filepath:2}
        filename=`basename $file`

        echo $filepath
        echo $subpath
        echo $filename

        if [ ! -d $2/$subpath/ ]; then
            #statements
            # echo "not exist"
            mkdir -p $2/$subpath/
        fi
        if test -f $file
        then
            $luajit -b $file $2/$subpath/$filename
        fi
    done
}

function copy() {
    echo $1
    echo $2
    for file in $1
    do
        echo $file
        filepath=`dirname $file`
        subpath=${filepath:2}
        filename=`basename $file`

        echo $filepath
        echo $subpath
        echo $filename

        if [ ! -d $2/$subpath/ ]; then
            #statements
            # echo "not exist"
            mkdir -p $2/$subpath/
        fi
        if test -f $file
        then
            # $luajit -b $file ./gamebin/$subpath/$filename
            if [ "${filename##*.}" != "so" ]; then
                cp $file $2/$subpath/$filename
            fi
        fi
    done
}

if [ ! -d ./out ]; then
    #statements
    # echo "not exist"
    mkdir -p ./out
fi


cur=`pwd`

cd $cur

echo $cur
# cp -R ../${a} ./out

rm -rf $cur/${a}
mkdir -p $cur/${a}/logs
mkdir -p $cur/${a}/3rd
mkdir -p $cur/${a}/3rd/lua-cmsgpack
mkdir -p $cur/${a}/3rd/lua-crypt
mkdir -p $cur/${a}/3rd/xxtea
mkdir -p $cur/${a}/conf
mkdir -p $cur/${a}/libs
mkdir -p $cur/${a}/libs/resty
mkdir -p $cur/${a}/logs
mkdir -p $cur/${a}/scripts
mkdir -p $cur/${a}/scripts_admin
mkdir -p $cur/${a}/utils
mkdir -p $cur/${a}/waf
mkdir -p $cur/${a}/waf/wafconf


compile "../${a}/*.lua" "$cur"
copy "../${a}/3rd/*" "$cur"
copy "../${a}/3rd/lua-cmsgpack/*" "$cur"
copy "../${a}/3rd/lua-crypt/*" "$cur"
copy "../${a}/3rd/xxtea/*" "$cur"
copy "../${a}/conf/*" "$cur"
compile "../${a}/libs/*" "$cur"
compile "../${a}/libs/resty/*" "$cur"
compile "../${a}/scripts/*" "$cur"
compile "../${a}/scripts_admin/*" "$cur"
compile "../${a}/utils/*" "$cur"
compile "../${a}/waf/*" "$cur"
copy "../${a}/waf/wafconf/*" "$cur"

rm ./${a}/conf/nginx.conf
mv ./${a}/conf/depnginx.conf ./${a}/conf/nginx.conf

tar -czvf ./out/${a}bin_$b.tar.gz $a

rm -rf ./$a
rm -rf ./out/$a
